#include <stdio.h>
#include "compile.h"

FILE *cont (FILE *out, FILE *f, char *title) {
  int c;
  char param[20];
  char *p;

  if (out==NULL) return NULL;
  if (f==NULL) return NULL;

  while (!feof(f)) {
    c=getc(f);
    if (c<0) break;
    if (c=='%') {
      p=param;
      *p++ = c;
      do {
        c=getc(f);
        *p++ = c;
      } while (c && (c!='%') && (c!='\n') && ((p-param)<sizeof(param)-2));
      *p=0;

      if (strcmp(param,"%cnt%")==0)
        fprintf(out,"%d",counter);
      else if (strcmp(param,"%nest%")==0)
        fprintf(out,"%d",nestoj);
      else if (strcmp(param,"%rad%")==0)
        fprintf(out,"%d",radikoj);
      else if (strcmp(param,"%title%")==0)
        fprintf(out,"%s",title);
      else if (strcmp(param,"%body%")==0)
        return f;
      else
        fprintf(out,"%s",param);
    } //if
    else
      fputc((char)c,out);
  }
  fclose(f);
  return NULL;
} //cont

FILE *prologue (FILE *out, char *name, char *title) {
  FILE *f;

  if (out==NULL) return NULL;
  f=fopen(name,"rb");
  if (f==NULL) return NULL;
  return cont(out,f,title);
} //prologue

void epilogue (FILE *out, FILE *f, char *title) {
  if (cont(out,f,title))
    fclose(f);
} //epilogue

void protofile (char *name, char *outname) {
  FILE *f;
  FILE *out;

  out=fopen(outname,"wb");
  if (out==NULL) return;

  f=prologue(out,name,"");
  if (f==NULL) return;
  fclose(f);
  fclose(out);
} //protofile
